﻿namespace WiseLink.RDS.Web
{
    using System;
    using System.Text.RegularExpressions;
    using System.Reflection;
    using System.Web.Mvc;
    using System.IO;
    using Telerik.Web.Mvc.UI;
    using System.Web.Hosting;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Linq;
    using WiseLink.RDS.Model.TroubleCodeRepository;
    [PopulateProductSiteMap(SiteMapName = "WebRDSSiteMap", ViewDataKey = "WebRDSFullSiteMap")]
    public class HomeController : Controller
    {
        private static readonly Regex ForbiddenExtensions = new Regex("dll|config", RegexOptions.IgnoreCase);
        
        public ActionResult FirstLook()
        {
            return View();
        }

        public ActionResult CodeFile(string file)
        {
            if (!file.StartsWith("~", StringComparison.OrdinalIgnoreCase))
            {
                return new EmptyResult();
            }

            file = Server.MapPath(file);
            string extension = Path.GetExtension(file);

            if (!System.IO.File.Exists(file) || ForbiddenExtensions.IsMatch(extension))
            {
                return new EmptyResult();
            }
            
            return PartialView((object)System.IO.File.ReadAllText(file));
        }
        
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }


        [HttpGet]
        public JsonResult GetDescription(string code, string carType, string version)
        {

            TroubleCodeRepository troubleCodeRep = new TroubleCodeRepository();
            CodeData codeData = troubleCodeRep.GetTroubleCode(carType, version, code);

            return Json(codeData, JsonRequestBehavior.AllowGet);

        }

        public string GetDescriptionTest(string code, string carType, string version)
        {
            TroubleCodeRepository troubleCodeRep = new TroubleCodeRepository();
            CodeData codeData = troubleCodeRep.GetTroubleCode(carType, version, code);

            if (codeData != null)
            {
                JsonResult jsonResult = Json(codeData, "text/plain");
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return serializer.Serialize(jsonResult.Data);
            }
            else
            {
                return "没有找到相应故障码";
            }



        }
    }
}